﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net.Core;
using Wintellect.PowerCollections;
using System.Threading;
using System.Diagnostics;
using System.Globalization;

namespace NHTrace
{
  public class Logger
  {
    public Logger(DebugProcessTracker processTracker, NHTracePackage package, int logCharSize)
    {
      _logCharSize = logCharSize;
      _package = package;
      _processTracker = processTracker;
    }

    private DebugProcessTracker _processTracker;
    private NHTracePackage _package;
    private int _logCharSize;

    public void LogEvents(LoggingEvent[] events)
    {
      if (_package.LogEnabled)
      {
        try
        {
          bool newMessagesAdded = false;
          foreach (var ev in events)
          {
            if (_processTracker.ProcessIsBeingDebugged(ev.Domain))
            {
              while (_logCharSize < _package.MessagesSize)
              {
                while ((_logCharSize < _package.MessagesSize) && (_package.FirstElementHasMessages()))
                  _package.RemoveFirstMessage();
              }

              _package.AddMessage(ev.TimeStamp, ev.RenderedMessage);
              newMessagesAdded = true;
            }

          }

          if (newMessagesAdded)
          {
            _package.WriteMessagesToWindow();
          }
        }
        catch (Exception ex)
        {
          Trace.WriteLine(ex.ToString());
          throw;
        }
      }
    }

    private void writeStartDebugMessage()
    {
      if (_package.LogEnabled)
      {
        DateTime now = DateTime.Now;
        _package.AddMessage(now, string.Format("{0} Debug started", now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)));

        _package.WriteMessagesToWindow();
      }
    }

    private void writeEndDebugMessage()
    {
      if (_package.LogEnabled)
      {
        DateTime now = DateTime.Now;
        _package.AddMessage(now, string.Format("{0} Debug stopped", now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture)));

        _package.WriteMessagesToWindow();
      }
    }

    public void Initialize()
    {
      writeStartDebugMessage();
    }

    public void Terminate()
    {
      writeEndDebugMessage();
    }
  }
}
